package pers.w.chaptertalk.reader;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pers.w.chaptertalk.R;
import pers.w.chaptertalk.funs.Fun;
import pers.w.chaptertalk.funs.IReader;

class Talks implements IReader {
    private static final String TAG = "Talks";
    private ReaderActivity reader;
    private EditText et_talk;
    private LinearLayout layout;
    final SimpleAdapter adapter;
    private List<Map<String, String>> talkItems;
    private String tag, bookName, bookAuthor, chapterName;
    private int chapterIndex, talkPage;
    private static String TALKER = "talker", TALK_CONTENT = "content", TIER_AND_TIME = "tier_and_time";
    private long sendTime = 0;
    private static int PAGE_CONTENT_SIZE = 20;
  //  private boolean sentNewTalk = false;
    private String username = (String) Fun.SHARE_MAP.get(R.string.prompt_username);
    private String password = (String) Fun.SHARE_MAP.get(R.string.prompt_password);

    Talks(ReaderActivity activity) {
        reader = activity;
        layout = reader.findViewById(R.id.ll_talks);

        et_talk = reader.findViewById(R.id.et_sendTalk);
        talkItems = new ArrayList<>();
        adapter = new SimpleAdapter(reader, talkItems, R.layout.talk_item_layout,
                new String[]{TALKER, TALK_CONTENT, TIER_AND_TIME},
                new int[]{R.id.tv_talker, R.id.tv_talk_content, R.id.tv_tier_and_time});
        setListView();
        setBtn_send();
    }

    private float lv_pointY;
    private boolean lv_isLastView;

    @SuppressLint("ClickableViewAccessibility")
    private void setListView() {
        ListView lv_talks = reader.findViewById(R.id.lv_talks);
        lv_talks.setAdapter(adapter);

        lv_talks.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                lv_isLastView = firstVisibleItem + visibleItemCount >= totalItemCount;
            }
        });
        lv_talks.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (lv_isLastView)
                        lv_pointY = (int) event.getY();
                    else
                        lv_pointY = -1;
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (lv_pointY > 0 && event.getY() - lv_pointY < 0) {
                        if (reader.pb_loading.getVisibility() != View.VISIBLE) {
                            reader.pb_loading.setVisibility(View.VISIBLE);
                            reader.showMsg("上拉加载更多");
                        }
                        return true;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    reader.pb_loading.setVisibility(View.INVISIBLE);
                    reader.hideMsg();
                    if (lv_pointY > 0 && event.getY() - lv_pointY < 10) {
                        Log.d(TAG, "onTouch: 上拉加载");
                        reader.hideMsg();
//                        if (sentNewTalk) {
//                            talkPage = 0;
//                            sentNewTalk = false;
//                            getTalksFromTag();
//                        } else {
                            if (talkItems.size() < (talkPage + 1) * PAGE_CONTENT_SIZE) {//现有的item数量小于这个页面该有的总数量，说明已经加载完了
                                Toast.makeText(reader, "没有更多了", Toast.LENGTH_SHORT).show();
                            } else if (Fun.isNetworkConnected(reader)) {
                                talkPage++;
                                getTalksFromTag();
                            }
                        //}
                        return true;
                    }
                    break;
            }
            return false;
        });
    }


    private void setBtn_send() {
        Button btn_sendTalk = reader.findViewById(R.id.btn_sendTalk);
        btn_sendTalk.setOnClickListener(v -> {
            if (et_talk.hasFocus()) {
                InputMethodManager imm = (InputMethodManager) reader.getSystemService(Activity.INPUT_METHOD_SERVICE);
                if (imm != null) imm.hideSoftInputFromWindow(et_talk.getWindowToken(), 0);
                et_talk.clearFocus();
            }
            if (username == null || password == null) {
                reader.showToask("请先登录");
                return;
            }
            if (System.currentTimeMillis() - sendTime < 2000)
                reader.showToask("2秒可以发送一次！");
            String talkContent = et_talk.getText().toString();
            if (talkContent.length() < 3)
                reader.showToask("最少3个字！");
            else if (talkContent.length() > 100)
                reader.showToask("最多100个字！");
            else if (Fun.isNetworkConnected(reader)) {
                sendTime = System.currentTimeMillis();
                final String url = reader.getString(R.string.server_address) + "sendtalk.php";
                et_talk.setText("");

                new Thread(() -> {
                    Connection conn = Jsoup.connect(url);
                    conn.data("book", bookName);
                    conn.data("auth", bookAuthor);
                    conn.data("chapter", chapterName);
                    conn.data("t", tag);
                    conn.data(USER, username);
                    conn.data(PASSWORD, password);
                    conn.data("e", Fun.webEncrypted(username, password));
                    conn.data("content", talkContent);
                    conn.timeout(5000);
                    Document doc = null;
                    try {
                        doc = conn.post();
                    } catch (IOException e) {
                        if (Fun.isDebug()) e.printStackTrace();
                    }

                    Document finalDoc = doc;
                    reader.runOnUiThread(()->{
                        if (finalDoc != null && finalDoc.text().indexOf(SUCCESS) == 0) {
                            if (Fun.isDebug()) Log.d(TAG, "Talks web ret:" + finalDoc.text());
                            reader.showToask("发送成功！");
                            talkPage = 0;
                            getTalksFromTag();
                        } else {
                            reader.showToask("发送失败！"+reader.getString(R.string.server_error));
                            // sentNewTalk = false;
                        }
                    });

                }).start();
            }
        });
    }

    boolean isVisibility() {
        return layout.getVisibility() == View.VISIBLE;
    }

    void show(String tag) {
        if (!tag.equals(this.tag)) {
            this.tag = tag;
            talkPage = 0;
            getTalksFromTag();
        }

        layout.setVisibility(View.VISIBLE);
        layout.startAnimation(reader.ltoC);
        if (reader.controlWindow.isVisibility()) reader.controlWindow.setVisibility(false);
        if (reader.settingWindow.isVisibility()) reader.settingWindow.setVisibility(false);
    }

    void hide() {
        layout.setVisibility(View.INVISIBLE);
        layout.startAnimation(reader.ctoL);
    }

    void setInfo(String bookName, String bookAuthor, String chapterName, int chapterIndex) {
        this.bookAuthor = bookAuthor;
        this.bookName = bookName;
        this.chapterName = chapterName;
        this.chapterIndex = chapterIndex;
        talkPage = 0;
    }

    //  private final Object object = new Object();

    private void getTalksFromTag() {
        final String getTalksStr = reader.getString(R.string.server_address) + "talk.php";

        if (talkPage == 0 && talkItems.size() > 0) {
            talkItems.clear();
            synchronized (adapter) {
                adapter.notify();
            }
        }
      //  String url = String.format(getTalksStr, bookName, bookAuthor, chapterName, tag, talkPage);
        new Thread(() -> {
            Document doc = null;
          //  ?book=%s&auth=%s&chapter=%s&t=%s&page=%d
            Connection conn =Jsoup.connect(getTalksStr);
            conn.timeout(5000);
            conn.data("book",bookName);
            conn.data("auth",bookAuthor);
            conn.data("chapter",chapterName);
            conn.data("t",tag);
            conn.data("page", String.valueOf(talkPage) );

            try {
                doc = conn.post();
            } catch (IOException e) {
                if (Fun.isDebug()) e.printStackTrace();
            }
            if (doc != null) {
                if (Fun.isDebug()) Log.d(TAG, "Talks web ret:" + doc.text());
                Elements talks = doc.select("div");
                if (talks.size() > 0) {

                    HashMap<String, String> talk;
                    Element e;
                    final String formatString = reader.getString(R.string.tier_and_time);
                    synchronized (adapter) {
                        for (int i = 0; i < talks.size(); i++) {
                            e = talks.get(i);
                            talk = new HashMap<>();
                            talk.put(TALKER, e.child(0).text());
                            talk.put(TALK_CONTENT, e.child(1).text());
                            talk.put(TIER_AND_TIME, String.format(formatString, e.child(3).text(), e.child(2).text()));
                            talkItems.add(talk);
                            //talkItems.add
                        }
                    }

                    Message msg = reader.handler.obtainMessage(HANDLER_TALKS_UPDATE);
                    reader.handler.sendMessage(msg);
                }
            }
        }).start();
    }


    void getTalksCount() {
        if (Fun.isNetworkConnected(reader)) {
            final String getTalksCountStr = reader.getString(R.string.server_address) + "talk.php";

           // String url = String.format(getTalksCountStr, bookName, bookAuthor, chapterName);
            new Thread(() -> {
                //?book=%s&auth=%s&chapter=%s&count=count
                Document doc = null;
                Connection conn =Jsoup.connect(getTalksCountStr);
                conn.timeout(5000);
                conn.data("book",bookName);
                conn.data("auth",bookAuthor);
                conn.data("chapter",chapterName);
                conn.data("count","count");

                try {
                    doc = conn.timeout(5000).post();
                } catch (IOException e) {
                    if (Fun.isDebug()) e.printStackTrace();
                }
                if (doc != null) {
                    Elements tags = doc.select("div");
                    if (tags.size() > 0) {
                        HashMap<String, String> talkTags = new HashMap<>();
                        for (int i = tags.size() - 1; i >= 0; i--) {//这里child 0就是tag，1就是数量
                            talkTags.put(tags.get(i).child(0).text(), tags.get(i).child(1).text());
                        }
                        Message msg = reader.handler.obtainMessage(HANDLER_TALKS_COUNT);
                        msg.arg1 = chapterIndex;
                        msg.obj = talkTags;
                        reader.handler.sendMessage(msg);
                    }
                }
            }).start();
        }
    }
}
